<template>
  <div class="box">
    <van-sticky>
      <div class="navbar">
        <van-icon name="cross" class="navcross" @click="closeCity" />
        <span class="nav-title">当前城市-{{ $store.state.cityName }}</span>
      </div>

      <van-search
        v-model="iptVal"
        show-action
        placeholder="请输入城市名或拼音"
        @search="onSearch"
        @cancel="onCancel"
        @input="onInput"
      />
    </van-sticky>
    <cityList v-if="blockShow == 1" :cityList="cityList" />
    <searchList v-else-if="blockShow == 2" :searchList="searchList" />
    <div class="nolist" v-if="blockShow == 3">
      <img src="../assets/images/city.png" />
      <p>没有找到匹配的城市</p>
    </div>
  </div>
</template>

<script>
import http from "../request/http";
import cityList from "./cityList";
import searchList from "./searchList";
export default {
  name: "City",
  data() {
    return {
      iptVal: "",
      blockShow: 1,
      cityList: [],
      originalcity: [],
      arr: []
    };
  },
  components: {
    cityList,
    searchList
  },
  computed: {
    searchList() {
      const arr = this.originalcity.filter(p => {
        return p.name.includes(this.iptVal) || p.pinyin.includes(this.iptVal);
      });
      this.arr = arr;
      if (arr.length == 0) {
        this.blockShow = 3;
        return [];
      }
      return arr;
    }
  },
  methods: {
    onInput() {
      this.blockShow = 2;
    },
    onSearch() {
      if (this.arr.length == 0) {
        this.blockShow = 3;
      }
    },
    onCancel() {
      this.blockShow = 1;
    },
    closeCity() {
      this.$router.back();
    },
    handleCityData(cities) {
      const letterArr = [];
      const newCities = [];
      for (let code = 65; code < 91; code++) {
        letterArr.push(String.fromCharCode(code));
      }
      letterArr.forEach(letter => {
        const list = cities.filter(
          item => item.pinyin.substring(0, 1).toUpperCase() === letter
        );

        if (list.length > 0) {
          newCities.push({
            type: letter,
            list: list
          });
        }
      });
      return newCities;
    }
  },
  mounted() {
    http({
      url: "/gateway?k=6838258",
      headers: {
        "X-Host": "mall.film-ticket.city.list"
      }
    }).then(res => {
      this.cityList = this.handleCityData(res.data.cities);
      this.originalcity = res.data.cities;
    });
  }
};
</script>
<style scoped>
.navbar{
    height:50px;
    line-height:50px;
    text-align:center;

}
.van-icon{
    text-align:left;
}
.nav-title{
    font-size:20px;
}
.van-index-anchor{
    background-color:red;
}
</style>
